$(function() {

	/**
	 * 首页文章列表
	 */
	var $articles = $('#articles');
	common.ajax($articles, 'listArticle', function(data) {
		common.render($articles, $('#articlesTpl'), {
			articles: data.result.list
		});

		/* 
		 * ejs template（相比lodash template更专业，它有内置函数和页面包括等功能；
		 * 1、需要注意EJS分Node端和浏览器
		 * 2、浏览器端EJS不支持include，有一种模拟方式：http://www.zhixing123.cn/jsp/33163.html
		 * 3、浏览器端EJS HTML不解析原样输出
		 * 所以浏览器端，不建议使用EJS。
			// 加载外部的一个EJS模版文件
			var html = new EJS({ url: "articles.ejs"}).render({ articles: data.result.list, address: '<address>重庆</address>'});
			// 加载HTML里内嵌的EJS模版内容
			// var html = new EJS({ text: $('#articlesTpl').html() }).render({ articles: data.result.list });
			$articles.append(html);
		 */

		/* handlerbar */
	});

	/**
	 * 首页左侧阅读排行
	 */
	var $readRanks = $('#readRanks');
	common.ajax($readRanks, 'listReadRank', function(data) {
		common.render($readRanks, $('#readRankTpl'), {
			readRanks: data.result
		});
	})

	/**
	 * 登录的相关功能
	 */
	var $loginCode = $('#loginCode');
	var $loginPassword = $('#loginPassword');
	var $rememberMe = $('#rememberMe');
	var $loginButton = $('#loginButton');
	$loginButton.click(function() {
		setLoginInfoToCookie();
	});
	// 记住密码的功能实现
	var loginCodeInCookie = $.cookie('loginCode');
	var loginPasswordInCookie = $.cookie('loginPassword');
	var rememberMeInCookie = $.cookie('rememberMe');
	if (loginCodeInCookie) {
		$loginCode.val(loginCodeInCookie);
	}
	if (loginPasswordInCookie) {
		$loginPassword.val(loginPasswordInCookie);
	}
	if (rememberMeInCookie) {
		$rememberMe.prop('checked', true);
	}

	function setLoginInfoToCookie() {
		if ($rememberMe.prop('checked')) {
			// jquery.cookie.js的更多使用，请参考：http://www.cnblogs.com/afuge/archive/2013/07/03/3169048.html
			$.cookie('loginCode', $loginCode.val(), {
				expires: 7
			});
			$.cookie('loginPassword', $loginPassword.val(), {
				expires: 7
			});
			$.cookie('rememberMe', $rememberMe.val(), {
				expires: 7
			});
		} else {
			$.cookie('loginCode', null);
			$.cookie('loginPassword', null);
			$.cookie('rememberMe', null);
		}
	}

	/**
	 *  注册的相关功能
	 */
	var $myModal1 = $('#myModal1');
	var $registerCode = $('#registerCode');
	var $registerPassword = $('#registerPassword');
	var $registerConfirmPassword = $('#registerConfirmPassword');
	var $registerBtn = $('#registerBtn');

	// 模态框显示时光标聚焦
	$myModal1.on('show.bs.modal', function(e) {});

	// 模态框隐藏时把内容清除掉
	$myModal1.on('hidden.bs.modal', function(e) {
		$registerCode.val('');
		$registerCode.parent().removeClass().addClass('form-group');
		$registerCode.nextAll().remove();
		$registerPassword.val('');
		$registerPassword.parent().removeClass().addClass('form-group');
		$registerPassword.nextAll().remove();
		$registerConfirmPassword.val('');
		$registerConfirmPassword.parent().removeClass().addClass('form-group');
		$registerConfirmPassword.nextAll().remove();
	});

	// 注册前验证
	var hasErrorAndFeedback = 'form-group has-error has-feedback';
	var hasSuccessAndFeedback = 'form-group has-success has-feedback';
	var hasErrorIcon = '<span class="glyphicon glyphicon-remove form-control-feedback"></span>';
	var hasSuccessIcon = '<span class="glyphicon glyphicon-ok form-control-feedback"></span>';
	// 针对账号的验证
	var setTimeoutId;
	$registerCode.keyup(function() {
		clearTimeout(setTimeoutId);
		setTimeoutId = setTimeout(function() {
			validateRegisterCode();
		}, 300)
	});

	function validateRegisterCode() {
		var registerCodeVal = $registerCode.val().trim();
		if (registerCodeVal === '') {
			$registerCode.parent().removeClass().addClass(hasErrorAndFeedback);
			$registerCode.nextAll().remove();
			$registerCode.after(hasErrorIcon + '<div class="invalid">帐号不能为空！</div>');
			return false;
		} else if (registerCodeVal.length > 12) {
			$registerCode.parent().removeClass().addClass(hasErrorAndFeedback);
			$registerCode.nextAll().remove();
			$registerCode.after(hasErrorIcon + '<div class="invalid">帐号不能长于12位！</div>');
			return false;
		} else {
			// 当帐号在JS端验证通过时，再向服务器请求，此帐号是否存在
			$.get(common.path + 'isExist', {
				code: registerCodeVal,
				random: Math.random()
			}, function(data) {
				if (data.code == 200) {
					$registerCode.parent().removeClass().addClass(hasSuccessAndFeedback);
					$registerCode.nextAll().remove();
					$registerCode.after(hasSuccessIcon);
					$registerBtn.prop('disabled', false);
				} else {
					$registerCode.parent().removeClass().addClass(hasErrorAndFeedback);
					$registerCode.nextAll().remove();
					$registerCode.after(hasErrorIcon + '<div class="invalid">帐号已存在！</div>');
					$registerBtn.prop('disabled', true);
				}
			});
			return true;
		}
	}

	// 针对密码的验证
	$registerPassword.keyup(function() {
		validateRegisterPassword();
		validateRegisterConfirmPassword();
	});

	function validateRegisterPassword() {
		var registerPasswordVal = $registerPassword.val().trim();
		if (registerPasswordVal.length > 12 || registerPasswordVal.length < 6) {
			$registerPassword.parent().removeClass().addClass(hasErrorAndFeedback);
			$registerPassword.nextAll().remove();
			$registerPassword.after(hasErrorIcon + '<div class="invalid">密码必须在6~12位之间！</div>');
			return false;
		} else {
			$registerPassword.parent().removeClass().addClass(hasSuccessAndFeedback);
			$registerPassword.nextAll().remove();
			$registerPassword.after(hasSuccessIcon);
			return true;
		}
	}
	// 针对确认密码的验证
	$registerConfirmPassword.keyup(function() {
		validateRegisterConfirmPassword();
	});

	function validateRegisterConfirmPassword() {
		var registerPasswordVal = $registerPassword.val().trim();
		var registerConfirmPasswordVal = $registerConfirmPassword.val().trim();
		if (registerConfirmPasswordVal != registerPasswordVal) {
			$registerConfirmPassword.parent().removeClass().addClass(hasErrorAndFeedback);
			$registerConfirmPassword.nextAll().remove();
			$registerConfirmPassword.after(hasErrorIcon + '<div class="invalid">确认密码必须与原密码一致！</div>');
			return false;
		} else {
			$registerConfirmPassword.parent().removeClass().addClass(hasSuccessAndFeedback);
			$registerConfirmPassword.nextAll().remove();
			$registerConfirmPassword.after(hasSuccessIcon);
			return true;
		}
	}

	// 进行注册
	$registerBtn.click(function() {
		var result = true;

		if (!validateRegisterCode() | !validateRegisterPassword() | !validateRegisterConfirmPassword()) {
			result = false;
		}

		// 验证成功后提交
		if (result) {
			var $btn = $(this).button('loading')
			var param = {
				'user.code': $registerCode.val().trim(),
				'user.password': $registerPassword.val().trim(),
				'date': new Date().getTime()
			}
			$.get(common.path + 'register', param, function(data) {
				if (data.code == 200) {
					$btn.button('reset')
					$myModal1.modal('hide');
					layer.msg('注册成功！');
				} else {
					$btn.button('reset')
					layer.msg('注册失败！可能的原因是：' + data.reason);
				}
			})
		}
	});
});